package com.course02.order_backend.config.Ost;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * Spring Security配置类，管理接口访问权限和密码加密
 * @author 开发者名称
 */
@Configuration
@EnableWebSecurity
@Order(1) // 确保配置优先加载，避免被其他配置覆盖
public class SecurityConfig {

    /**
     * 注册BCrypt密码编码器Bean，供服务层注入使用
     * @return BCryptPasswordEncoder实例
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置接口安全规则：放行注册接口，其他接口需认证
     * @param http HttpSecurity对象
     * @return 配置好的SecurityFilterChain
     * @throws Exception 配置过程中可能抛出的异常
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable()) // 开发阶段关闭CSRF防护，允许跨域请求
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/api/user/register").permitAll() // 注册接口允许匿名访问
                        .anyRequest().authenticated() // 其他接口需要认证
                );
        return http.build();
    }
}